//
//  ClubForumSearchViewController.swift
//  77Club
//
//  Created by Apple on 2025/1/6.
//

import UIKit

class ClubForumSearchViewController: ClubBaseViewController {

    private let searchTextF = c_make_ex(UITextField.self)
        .corner(15).bgColor("#7B7D80".toColor.alpha(0.08))
        .color("#2E3033").font(12.font_medium)
        .placeholder("请输入关键进行搜索").end()
    private let cancelButton = c_make_ex(UIButton.self)
        .text("取消").color("#47494D").font(15.font_semiBold).end()
    private let historyLabel = c_make_ex(UILabel.self)
        .text("历史记录").color("#1A1A1A").font(14.font_semiBold).end()
    private let delButton = c_make_ex(UIButton.self)
        .image("Home_search_delete").end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var historyData = [String]()
    
    var model: ClubGameCommunityModel?
    var communityId: String = ""
    
    //1.广场论坛搜索 0.广场动态搜索
    var type: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            searchTextF
            cancelButton
            delButton
            historyLabel
            collectionView
        }
        
        searchTextF.style { v in
            v.placehold("#AEB0B3".toColor, font: 12.font_medium)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 26, height: 30))
            let searchImg = UIImageView(frame: CGRect(x: 6, y: 7, width: 16, height: 16))
            searchImg.image = "Home_searchGray".toImage
            leftV.addSubview(searchImg)
            v.leftView = leftV
            v.leftViewMode = .always
            v.returnKeyType = .search
            v.delegate = self
        }
        
        searchTextF.leading(12.0.Scale).top(.statusHeight + 8.0.Scale).width(295.0.Scale).height(30)
        cancelButton.trailing(0).height(30)
        cancelButton.CenterY == searchTextF.CenterY
        cancelButton.Leading == searchTextF.Trailing
        historyLabel.leading(12.0.Scale)
        historyLabel.Top == searchTextF.Bottom + 16.0.Scale
        delButton.trailing(0).width(44).height(32)
        delButton.CenterY == historyLabel.CenterY
        collectionView.leading(0).trailing(0).height(150.0.Scale)
        collectionView.Top == historyLabel.Bottom + 12.0.Scale
        
        let layoutH = UICollectionViewLeftAlignedLayout()
        layoutH.minimumLineSpacing = 8
        layoutH.minimumInteritemSpacing = 8
        layoutH.scrollDirection = .vertical
        layoutH.sectionInset = UIEdgeInsets(top: 0, left: 12.0.Scale, bottom: 0, right: 12.0.Scale)
        collectionView.collectionViewLayout = layoutH
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGamesSearchCell.self, forCellWithReuseIdentifier: "ClubGamesSearchHistoryCell")
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        historyLabel.isHidden = true
        delButton.isHidden = true
        collectionView.isHidden = true
        
        loadData()
        
        cancelButton.addTarget(self, action: #selector(clickDismissButton), for: .touchUpInside)
        delButton.addTarget(self, action: #selector(clickDeleteButton), for: .touchUpInside)
    }


    private func loadData(){
        
        if communityId.count == 0 {
            
            if type == 1 {
                
                if let history = UserDefaultsManager.getString(forKey: .squareSearchHistory), history.count > 0 {
                    historyLabel.isHidden = false
                    delButton.isHidden = false
                    collectionView.isHidden = false
                    self.historyData = history.components(separatedBy: ",")
                    collectionView.reloadData()
                }else{
                    historyData.removeAll()
                    historyLabel.isHidden = true
                    delButton.isHidden = true
                    collectionView.isHidden = true
                    collectionView.reloadData()
                }
            }else{
                
                if let history = UserDefaultsManager.getString(forKey: .dynamicSearchHistory), history.count > 0 {
                    historyLabel.isHidden = false
                    delButton.isHidden = false
                    collectionView.isHidden = false
                    self.historyData = history.components(separatedBy: ",")
                    collectionView.reloadData()
                }else{
                    historyData.removeAll()
                    historyLabel.isHidden = true
                    delButton.isHidden = true
                    collectionView.isHidden = true
                    collectionView.reloadData()
                }
            }
            
        }else{
            
            if let history = UserDefaultsManager.getString(forKey: .forumSearchHistory), history.count > 0 {
                historyLabel.isHidden = false
                delButton.isHidden = false
                collectionView.isHidden = false
                self.historyData = history.components(separatedBy: ",")
                collectionView.reloadData()
            }else{
                historyData.removeAll()
                historyLabel.isHidden = true
                delButton.isHidden = true
                collectionView.isHidden = true
                collectionView.reloadData()
            }
        }
        
        
    }
    
    @objc private func clickDeleteButton(){
        
        if communityId.count == 0 {
            if type == 1{
                UserDefaultsManager.removeForKey(forKey: .squareSearchHistory)
            }else{
                UserDefaultsManager.removeForKey(forKey: .dynamicSearchHistory)
            }
        }else{
            UserDefaultsManager.removeForKey(forKey: .forumSearchHistory)
        }
        
        historyData.removeAll()
        historyLabel.isHidden = true
        delButton.isHidden = true
        collectionView.isHidden = true
        collectionView.reloadData()
    }
    
    private func pushToListVC(keyword: String){
        
        if communityId.count == 0 {
            
            if type == 1{
                
                let listVC = ClubSquareSearchListViewController()
                listVC.keyword = keyword
                listVC.updateHistoryData = {
                    self.loadData()
                }
                self.navigationController?.pushViewController(listVC, animated: true)
            }else{
                
                let listVC = ClubDynamicSearchListViewController()
                listVC.keyword = keyword
                listVC.updateHistoryData = {
                    self.loadData()
                }
                self.navigationController?.pushViewController(listVC, animated: true)
            }
            
        }else{
            
            let listVC = ClubForumSearchListViewController()
            listVC.communityId = communityId
            listVC.model = model
            listVC.keyword = keyword
            listVC.updateHistoryData = {
                self.loadData()
            }
            self.navigationController?.pushViewController(listVC, animated: true)
        }
    }
    
    @objc private func clickDismissButton(){
        self.navigationController?.popViewController(animated: true)
    }
    
}

extension ClubForumSearchViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.historyData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ClubGamesSearchHistoryCell", for: indexPath) as? ClubGamesSearchCell else { return UICollectionViewCell() }
        cell.titleString = historyData[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let keyword = historyData[indexPath.row]
        self.pushToListVC(keyword: keyword)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let name = historyData[indexPath.row]
        let font = 12.font_medium
        let attributedText = NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: font as Any])

        // 计算文本宽度
        let size = attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size
        let width = size.width + 24.0.Scale
        
        return CGSize(width: width, height: 24.0.Scale)
    }
    
    // 监听 return 键（即搜索按钮）被点击
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 隐藏键盘
        textField.resignFirstResponder()
        // 执行搜索操作
        searchAction(text: textField.text)
        return true
    }
    
    // 搜索操作的逻辑
    func searchAction(text: String?) {
        if let searchText = text, !searchText.isEmpty {
            searchTextF.text = ""
            
            if communityId.count == 0 {
                
                if type == 1 {
                    
                    if var history = UserDefaultsManager.getString(forKey: .squareSearchHistory), history.count > 0 {
                        history.append("," + searchText)
                        UserDefaultsManager.setString(history, forKey: .squareSearchHistory)
                        self.historyData.append(searchText)
                        
                    }else{
                        var tempArray = [String]()
                        tempArray.append(searchText)
                        let wordArray = tempArray.joined(separator: ",")
                        UserDefaultsManager.setString(wordArray, forKey: .squareSearchHistory)
                        self.historyData = tempArray
                    }
                }else{
                    
                    if var history = UserDefaultsManager.getString(forKey: .dynamicSearchHistory), history.count > 0 {
                        history.append("," + searchText)
                        UserDefaultsManager.setString(history, forKey: .dynamicSearchHistory)
                        self.historyData.append(searchText)
                        
                    }else{
                        var tempArray = [String]()
                        tempArray.append(searchText)
                        let wordArray = tempArray.joined(separator: ",")
                        UserDefaultsManager.setString(wordArray, forKey: .dynamicSearchHistory)
                        self.historyData = tempArray
                    }
                }                
            }else{
                if var history = UserDefaultsManager.getString(forKey: .forumSearchHistory), history.count > 0 {
                    history.append("," + searchText)
                    UserDefaultsManager.setString(history, forKey: .forumSearchHistory)
                    self.historyData.append(searchText)
                    
                }else{
                    var tempArray = [String]()
                    tempArray.append(searchText)
                    let wordArray = tempArray.joined(separator: ",")
                    UserDefaultsManager.setString(wordArray, forKey: .forumSearchHistory)
                    self.historyData = tempArray
                }
            }
            historyLabel.isHidden = false
            delButton.isHidden = false
            collectionView.isHidden = false
            collectionView.reloadData()
            self.pushToListVC(keyword: searchText)
        }
    }
}
